package org.jeecg.modules.orderForm.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.metal.OceanTheme;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.BigDecimalUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.orderForm.entity.OrderForm;
import org.jeecg.modules.orderForm.entity.OrderStatistics;
import org.jeecg.modules.orderForm.service.IOrderFormService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

/**
 * @Title: Controller
 * @Description: 订单
 * @author： jeecg-boot
 * @date：   2021-03-30
 * @version： V1.0
 */
@RestController
@RequestMapping("/orderForm/orderForm")
@Slf4j
public class OrderFormController {
	@Autowired
	private IOrderFormService orderFormService;
	@Autowired
	private ISysUserService sysUserService;

	/**
	 *   获取子管里的提成数
	 * @param orderForm
	 * @return
	 */
	@GetMapping(value = "/getTakeManagerMoney")
	public Result<OrderForm> getTakeManagerMoney(OrderForm orderForm) {
		Result<OrderForm> result = new Result<OrderForm>();
		try {
			BigDecimal rate = BigDecimalUtil.div(orderForm.getCommissionRate(),"100");
			String takeManagerMoney= BigDecimalUtil.mul(orderForm.getCost(),rate.toString()).toString();
			orderForm.setTakeManagerMoney(takeManagerMoney);
			result.setResult(orderForm);
			result.success("计算成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("计算子管理的提成数失败，请输入正确的金额数值！");
		}
		return result;
	}


	/**
	 * 分页列表查询
	 * @param orderForm
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<OrderForm>> queryPageList(OrderForm orderForm,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		Result<IPage<OrderForm>> result = new Result<IPage<OrderForm>>();
		setOrderFormQueryEmpty(orderForm);
		QueryWrapper<OrderForm> queryWrapper = QueryGenerator.initQueryWrapper(orderForm, req.getParameterMap());
		Page<OrderForm> page = new Page<OrderForm>(pageNo, pageSize);
		IPage<OrderForm> pageList = orderFormService.page(page, queryWrapper);
		List<OrderForm> orderForms= pageList.getRecords();
	  	for(OrderForm order:orderForms){
		  SysUser user=sysUserService.getUserByName(order.getCreateBy());
		  order.setCreateByName(user.getRealname());
		}
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	/**
	 * 分页列表查询为了指派加价人员
	 * @param orderForm
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/listByAppoint")
	public Result<IPage<OrderForm>> listByAppoint(OrderForm orderForm,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		Result<IPage<OrderForm>> result = new Result<IPage<OrderForm>>();
		setOrderFormQueryEmpty(orderForm);
		QueryWrapper<OrderForm> queryWrapper = QueryGenerator.initQueryWrapper(orderForm, req.getParameterMap());
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		//queryWrapper.eq("create_by",sysUser.getUsername());
		//queryWrapper.isNull("raise_number");
		queryWrapper.inSql("id","SELECT o.orderid from (SELECT  orderid,status from order_raise  GROUP BY orderid,status) o WHERE o.status!=1");
		Page<OrderForm> page = new Page<OrderForm>(pageNo, pageSize);
		IPage<OrderForm> pageList = orderFormService.page(page, queryWrapper);
		List<OrderForm> orderForms= pageList.getRecords();
		for(OrderForm order:orderForms){
			SysUser user=sysUserService.getUserByName(order.getCreateBy());
			order.setCreateByName(user.getRealname());
		}
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	public void   setOrderFormQueryEmpty(OrderForm orderForm){
		 /*if(oConvertUtils.isNotEmpty(orderForm.getTakeOrders())){//订单接单人模糊查询
			 orderForm.setTakeOrders("*"+orderForm.getTakeOrders()+"*");
		 }*/
		if(oConvertUtils.isNotEmpty(orderForm.getDemand())){//要求模糊查询
			orderForm.setDemand("*"+orderForm.getDemand()+"*");
		}
		if(oConvertUtils.isNotEmpty(orderForm.getTechnical())){//技术要求模糊查询
			orderForm.setTechnical("*"+orderForm.getTechnical()+"*");
		}
		if(oConvertUtils.isNotEmpty(orderForm.getOrderName())){//订单名称模糊查询
			orderForm.setOrderName("*"+orderForm.getOrderName()+"*");
		}
	}

	@RequestMapping(value = "/Statistics", method = RequestMethod.GET)
	public Result<OrderStatistics> Statistics(SysUser user,HttpServletRequest req){
		Result<OrderStatistics> result=new Result<OrderStatistics>();
		OrderStatistics orderStatistics=null;
		System.err.println("user.getUsername()-->"+user.getUsername());
		QueryWrapper<OrderForm> queryWrapper =new QueryWrapper<OrderForm>();
		queryWrapper.eq("take_orders",user.getUsername());
		queryWrapper.and(wrapper->wrapper.eq("order_status",4).or().eq("order_status",5));
		Integer finishNum= orderFormService.count(queryWrapper);

		QueryWrapper<OrderForm> dealNumqueryWrapper =new QueryWrapper<OrderForm>();
		dealNumqueryWrapper.eq("take_orders",user.getUsername());
		dealNumqueryWrapper.eq("order_status",5);
		Integer dealNum= orderFormService.count(dealNumqueryWrapper);

		QueryWrapper<OrderForm> refundNumqueryWrapper =new QueryWrapper<OrderForm>();
		refundNumqueryWrapper.eq("take_orders",user.getUsername());
		refundNumqueryWrapper.eq("order_status",4);
		Integer refundNum= orderFormService.count(refundNumqueryWrapper);
		String successRate="0.0%";
		if(finishNum!=0){
			 successRate=((double)dealNum/finishNum)*100+"%";
		}
		orderStatistics= new OrderStatistics(user.getUsername(),finishNum,dealNum,refundNum,successRate);
		result.setSuccess(true);
		result.setResult(orderStatistics);
		return result;
	}


	/**
	 *   添加
	 * @param orderForm
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<OrderForm> add(@RequestBody OrderForm orderForm) {
		Result<OrderForm> result = new Result<OrderForm>();
		try {
			if("0".equals(orderForm.getOrderType())){
				orderForm.setGrabTime(new Date());
			}
			orderFormService.save(orderForm);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 *  编辑
	 * @param orderForm
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<OrderForm> edit(@RequestBody OrderForm orderForm) {
		Result<OrderForm> result = new Result<OrderForm>();
		OrderForm orderFormEntity = orderFormService.getById(orderForm.getId());
		if(orderFormEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = orderFormService.updateById(orderForm);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}
	/**
	 *  修改状态
	 * @param orderForm
	 * @return
	 */
	@PutMapping(value = "/editByOrderStatus")
	public Result<OrderForm> editByOrderStatus(@RequestBody OrderForm orderForm) {
		Result<OrderForm> result = new Result<OrderForm>();
		OrderForm orderFormEntity = orderFormService.getById(orderForm.getId());
		if(orderFormEntity==null) {
			result.error500("未找到对应实体");
		}else {
		 	/*if(orderForm.getOrderStatus().equals(0)){//如抢到订单后不想做，需联系管理员还原抢单状态
				orderForm.setTakeOrders(null);
				orderForm.setRaiseNumber(null);
				//orderForm.setGrabTime(null);
			}*/
			boolean ok = orderFormService.updateById(orderForm);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}
	/**
	 *  抢单接口
	 * @param orderForm
	 * @return
	 */
	@PutMapping(value = "/grabEdit")
	public Result<OrderForm> grabEdit(@RequestBody OrderForm orderForm) {
		Result<OrderForm> result = new Result<OrderForm>();
		OrderForm orderFormEntity = orderFormService.getById(orderForm.getId());
		if(orderFormEntity.getOrderStatus()==-1){
			result.success("此订单已被删除！");
			result.setSuccess(false);
			return result;
		}
		if(orderFormEntity.getOrderStatus()!=6){
			result.success("手慢了此订单已被抢！");
			result.setSuccess(false);
			return result;
		}
		if(orderFormEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = orderFormService.updateById(orderForm);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}

	/**
	 *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<OrderForm> delete(@RequestParam(name="id",required=true) String id) {
		Result<OrderForm> result = new Result<OrderForm>();
		OrderForm orderForm = orderFormService.getById(id);

		if(orderForm==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = orderFormService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}

		return result;
	}

	/**
	 *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<OrderForm> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<OrderForm> result = new Result<OrderForm>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.orderFormService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 *  批量标记子管理已结算
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/MarkBatch")
	public Result<OrderForm> MarkBatch(@RequestParam(name="ids",required=true)String ids) {
		Result<OrderForm> result = new Result<OrderForm>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<OrderForm>();
			queryWrapper.in("id",Arrays.asList(ids.split(",")));
			List<OrderForm> orderForms=orderFormService.list(queryWrapper);
			for(OrderForm orderForm:orderForms){
				orderForm.setManagerClose(1);
			}
			if(orderForms.size()>0){
				orderFormService.updateBatchById(orderForms);
			}
			result.success("批量标记成功!");
		}
		return result;
	}

	/**
	 * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<OrderForm> queryById(@RequestParam(name="id",required=true) String id) {
		Result<OrderForm> result = new Result<OrderForm>();
		OrderForm orderForm = orderFormService.getById(id);
		if(orderForm==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(orderForm);
			result.setSuccess(true);
		}
		return result;
	}
	/**
	 * 通过id查询
	 * @param orderForm
	 * @return
	 */
	@GetMapping(value = "/checkOnlyNumber")
	public Result<OrderForm> checkOnlyNumber(OrderForm orderForm) {
		Result<OrderForm> result = new Result<OrderForm>();
		QueryWrapper<OrderForm> wrapper=new QueryWrapper<OrderForm>();
		wrapper.eq("order_number",orderForm.getOrderNumber());
	    Integer id =orderForm.getId();
		try{
			OrderForm oldOrder = null;
			if (oConvertUtils.isNotEmpty(orderForm.getId())) {
				oldOrder = orderFormService.getById(id);
			}
				OrderForm orderFormobj = orderFormService.getOne(wrapper);
				if(oConvertUtils.isNotEmpty(oldOrder) && oConvertUtils.isNotEmpty(orderFormobj)){
					if(oldOrder.getId().equals(orderFormobj.getId())) {
						result.setSuccess(true);
					}else {
						result.setSuccess(false);
					}
				}else {
					if(oConvertUtils.isNotEmpty(orderFormobj)) {
						result.setSuccess(false);
					}else {
						result.setSuccess(true);
					}
				}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(e.getMessage());
			return result;
		}
		return result;
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
		// Step.1 组装查询条件
		QueryWrapper<OrderForm> queryWrapper = null;
		try {
			String paramsStr = request.getParameter("paramsStr");
			if (oConvertUtils.isNotEmpty(paramsStr)) {
				String deString = URLDecoder.decode(paramsStr, "UTF-8");
				OrderForm orderForm = JSON.parseObject(deString, OrderForm.class);
				queryWrapper = QueryGenerator.initQueryWrapper(orderForm, request.getParameterMap());
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<OrderForm> pageList = orderFormService.list(queryWrapper);
		//导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "订单列表");
		mv.addObject(NormalExcelConstants.CLASS, OrderForm.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单列表数据", "导出人:Jeecg", "导出信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<OrderForm> listOrderForms = ExcelImportUtil.importExcel(file.getInputStream(), OrderForm.class, params);
				for (OrderForm orderFormExcel : listOrderForms) {
					orderFormService.save(orderFormExcel);
				}
				return Result.ok("文件导入成功！数据行数：" + listOrderForms.size());
			} catch (Exception e) {
				log.error(e.getMessage());
				return Result.error("文件导入失败！");
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
	}

}
